<template>
    <div class="wrapper">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        
        <!-- 卡片 -->
        <el-card class="box-card">
            <!-- 添加分类 -->
            <el-button type="primary" @click="addCommodityCategoriesInfo.dialogVisible = true;">添加商品</el-button>
            <!-- 添加分类对话框 -->
            <el-dialog
                title="添加分类"
                :visible.sync="addCommodityCategoriesInfo.dialogVisible"
                width="50%">
                    <el-form label-width="80px" :model="addCommodityCategoriesInfo.categories" :rules="addCommodityCategoriesInfo.rules" ref='addCommodityCategoriesRef'>
                        <el-form-item label="分类名称" prop="name">
                            <el-input v-model="addCommodityCategoriesInfo.categories.name"></el-input>
                        </el-form-item>
                        <el-form-item label="父级类别">
                            <el-cascader
                                v-model="addCommodityCategoriesInfo.fatherCategories"
                                :options="addCommodityCategoriesFaterData"
                                :props="{ checkStrictly: true , label: 'cat_name', value: 'cat_id'}"
                                clearable>
                            </el-cascader>
                        </el-form-item>
                    </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addCommodityCategoriesInfo.dialogVisible = false;resetFields()">取 消</el-button>
                    <el-button type="primary" @click="addCommodityCategoriesInfo.dialogVisible = false;addCommodityCategories()">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 表格 -->
            <el-table
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                :data="categorieslistData.data"
                style="width: 100%;margin-bottom: 20px;"
                row-key="cat_id"
                border
                ref='box'
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
                <el-table-column
                    type="index"
                    label="序号"
                    width="60">
                </el-table-column>
                <el-table-column
                    prop="cat_name"
                    label="名称"
                    width="300">
                </el-table-column>
                <el-table-column
                    prop="cat_deleted"
                    label="是否有效">
                    <template v-slot='scope'>
                        <i class="el-icon-check success" v-if="scope.row.cat_deleted === false"></i>
                        <i class="el-icon-close error" v-else></i>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="address"
                    label="级别">
                    <template v-slot="scope">
                        <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
                        <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
                        <el-tag v-else type="warning">三级</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="address"
                    label="操作">
                    <template v-slot="scope">
                        <el-button size="small" 
                            @click="handler_edit_data(scope.row)" 
                            icon="el-icon-edit"
                            type="primary"
                        >编辑</el-button>
                        <el-button size="small" 
                            @click="delete_commodity(scope.row.cat_id)"
                            icon="el-icon-delete"
                            type="danger"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 修改商品分类名称对话框 -->
            <el-dialog
                title="修改商品分类"
                :visible.sync="edit_categories_name.dialog"
                width="30%">
                <el-form :model="edit_categories_name" ref='edit_categories_name_ref' :rules='edit_categories_name.rules' label-width="80px">
                    <el-form-item label="分类名称" prop='value'>
                        <el-input ref="edit_categories_input" v-model="edit_categories_name.value"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="edit_categories_name.dialog = false;reset_commodity_categories_name()">取 消</el-button>
                    <el-button type="primary" @click="edit_categories_name.dialog = false;edit_commodity_name()">确 定</el-button>
                </span>
            </el-dialog>


            <!-- 分页功能区域 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="categoriesParams.pagenum"
                :page-sizes="[5, 10, 30, 50]"
                :page-size="5"
                layout="total, sizes, prev, pager, next, jumper"
                :total="categorieslistData.total">
            </el-pagination>
        </el-card>

        
    </div>
</template>

<script>
    export default {
        name: "Categories",
        data() {
            return {
                categoriesParams: {  //商品分类参数
                    type: [1, 2, 3],
                    pagenum: 1,
                    pagesize: 5
                },
                categorieslistData: { //商品分类列表数据
                    data: [],
                    total: 0,
                    pagenum: null,
                    pagesize: ''
                },
                addCommodityCategoriesInfo: {  //添加商品分类列表数据
                    dialogVisible: false,   //添加商品对话框
                    categories: {name: ''},  //新商品名称
                    fatherCategories: [],  //父级类别
                    rules: {name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]}
                },
                // 添加商品分类参数
                addCommodityCategoriesParams: {
                    cat_pid: 0,
                    cat_name: '',
                    cat_level: 0
                },
                addCommodityCategoriesFaterData: [],  //添加分类数据(只有第一层和第二层的数据)
                edit_categories_name: {  //修改分类名称
                    dialog: false,
                    rules: {value: [{required: true, message: '请输入分类名称', trigger: 'blur'}]},
                    value: '',
                    cat_id: '',
                    cat_name: ''
                },
                loading : true,
            }
        },
        created() {
            this.getCategoriesListData();
            this.getAddCommodityCategoriesFAterData();
        },
        methods: {
            // 获取商品分类数据
            async getCategoriesListData() {
                let {data:res} = await this.$http.get('/categories', {
                    params: this.categoriesParams
                })
                if(res.meta.status !== 200) return this.$message.error('获取商品分类失败');
                this.categorieslistData.data = res.data.result;
                this.categorieslistData.total = res.data.total;
                this.categorieslistData.pagenum = Number(res.data.pagenum);
                this.categorieslistData.pagesize = res.data.pagesize;
                this.loading = false;
            },
            // 获取添加商品父级数据
            async getAddCommodityCategoriesFAterData() {
                let {data:res} = await this.$http.get('/categories', {
                    params: {
                        type: 2,
                        pagenum: 1,
                        pagesize: 50
                    }
                });
                if(res.meta.status !== 200) return this.$message.error('获取商品分类失败');
                this.addCommodityCategoriesFaterData = res.data.result;
            },
            // 添加商品分类
            addCommodityCategories() {
                this.$refs.addCommodityCategoriesRef.validate(async valid => {
                    if(!valid) {
                        this.resetFields();
                        this.$message.error('分类名称不能为空')
                        return 
                    }
                    // 处理参数
                    // 分类名称
                    this.addCommodityCategoriesParams.cat_name = this.addCommodityCategoriesInfo.categories.name
                    // 父级ID
                    let len = this.addCommodityCategoriesInfo.fatherCategories.length;
                    if(len > 0) {
                        this.addCommodityCategoriesParams.cat_pid = this.addCommodityCategoriesInfo.fatherCategories[len-1]
                        // 分类层级
                        this.addCommodityCategoriesParams.cat_level = len;
                    }else {
                        this.addCommodityCategoriesParams.cat_pid = 0;
                        this.addCommodityCategories.cat_level = 0;
                    }
                    
                    // 发送修改请求
                    let {data:res} = await this.$http.post('/categories', this.addCommodityCategoriesParams);
                    if(res.meta.status !== 201) return this.$message.error('添加商品分类失败')
                    this.getCategoriesListData();
                    this.getAddCommodityCategoriesFAterData();
                    this.$message.success('添加商品分类成功');
                    this.resetFields();
                    this.addCommodityCategoriesInfo.fatherCategories = '';
                })
            },
            // 重置分类名称表单
            resetFields() {
                this.$refs.addCommodityCategoriesRef.resetFields();
            },
            // 处理编辑商品名称数据
            handler_edit_data({cat_id, cat_name}) {
                this.edit_categories_name.dialog = true;
                this.edit_categories_name.cat_id = cat_id;
                this.edit_categories_name.cat_name = cat_name;
                this.edit_categories_name.value = this.edit_categories_name.cat_name;
                this.$nextTick(() => {
                    this.$refs.edit_categories_input.focus()
                })
            },
            // 编辑商品名称
            async edit_commodity_name() {
                let {data:res} = await this.$http.put(`/categories/${this.edit_categories_name.cat_id}`, {
                    cat_name: this.edit_categories_name.value
                })
                if(res.meta.status !== 200) return this.$message.error('修改商品分类失败');
                this.getCategoriesListData();
                this.$message.success('修改商品分类成功');
                this.reset_commodity_categories_name();
            },
            // 重置编辑商品名称表单
            reset_commodity_categories_name() {
                this.$refs.edit_categories_name_ref.resetFields();
            },
            // 删除商品
            delete_commodity(id) {
                this.$messageBox.confirm('此操作将永久删除该分类, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let {data: res} = await this.$http.delete(`/categories/${id}`);
                    if(res.meta.status !== 200) return this.$message.error('删除商品分类失败');
                    this.getCategoriesListData();
                    this.getAddCommodityCategoriesFAterData();
                    this.$message({type: 'success', message: '删除成功!'});
                }).catch(() => {
                    this.$message({type: 'info', message: '已取消删除'});       
                });
            },
            
            // 分页功能方法
            handleSizeChange(value) {
                this.categoriesParams.pagesize = value;
                this.getCategoriesListData();
            },
            handleCurrentChange(value) {
                this.categoriesParams.pagenum = value;
                this.getCategoriesListData();
            }

        }
    };
    
</script>

<style lang='less' scoped>
    .wrapper{
        width: 100%;
        height: 0px;
        padding: 10px 20px;
        box-sizing: border-box;
        .success{
            background-color: #67c23a;
            font-size: 10px;
            color: white;
            width: 15px;
            height: 15px;
            text-align: center;
            line-height: 16px;
            border-radius: 50%;
        }
        .error{
            background-color: #f56c6c;
            font-size: 10px;
            color: white;
            width: 15px;
            height: 15px;
            text-align: center;
            line-height: 16px;
            border-radius: 50%;
        }
        .el-cascader{
            width: 100%;
        }
    }
</style>